//
//  TL_FeedbackSubViewController.m
//  WXReader
//
//  Created by Andrew on 2018/7/4.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_FeedbackSubViewController.h"

#import "TL_FeedbackTextViewTableViewCell.h"
#import "TL_FeedbackPhotoTableViewCell.h"
#import "TL_FeedbackContactTableViewCell.h"

#import "TL_TextView.h"

#import "TL_KeyboardManager.h"
#import "TL_FeedbackPhotoManager.h"

#import "TL_FeedbackCenterModel.h"

@interface TL_FeedbackSubViewController () <UITableViewDelegate, UITableViewDataSource> {
    TL_KeyboardManager *keyboardManager;
}

@property (nonatomic, strong) NSString *questionChooseString;

@property (nonatomic, strong) NSString *contentString;

@property (nonatomic, strong) NSString *contactString;

@property (nonatomic, strong) TL_FeedbackCenterModel *feedbackModel;

@property (nonatomic, assign) NSInteger questionSelectedIndex;

@property (nonatomic, strong) NSMutableArray *questionArray;

@property (nonatomic, assign) BOOL submitIsClick; // 提交按钮已点击

@end

@implementation TL_FeedbackSubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self createSubviews];
    [self netRequest];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self navigationCanSlidingBack:NO];
}

- (void)initialize {
    [self setNavigationBarTitle:self.navTitle ?:  WXLocalizedString(@"帮助中心")];
    self.navigationBar.navTitleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self hiddenNavigationBarLeftButton];
    
    self.submitIsClick = NO;
    
    self.questionArray = [[NSMutableArray alloc] init];
    
    UIButton *backButton = [TL_UIFactory buttonTypeCustomWithFont:nil textColor:nil target:self action:@selector(giveUpSubmit)];
    backButton.adjustsImageWhenHighlighted = NO;
    backButton.layer.masksToBounds = YES;
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 6, 12, 18)];
    [backButton setImage:[[UIImage imageNamed:@"public_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [backButton setTintColor:kBlackColor];
    [self.navigationBar addSubview:backButton];
    
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kHalfMargin);
        make.bottom.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    
    self.view.backgroundColor = kGrayViewColor;
    
    self.questionSelectedIndex = 0;
    
    UIButton *feedbackListButton = [TL_UIFactory buttonWithType:UIButtonTypeCustom backgroundColor:nil font:SYSTEM_FONT(13) textColor:[UIColor hex_9E6DFC] target:self action:@selector(submitInfo)];
    [feedbackListButton setTitle:WXLocalizedString(@"提交") forState:UIControlStateNormal];
    
    [self setNavigationBarRightButton:feedbackListButton];
    
    [feedbackListButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kMoreHalfMargin);
        make.size.mas_equalTo(feedbackListButton.w_textSize);
        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
    }];
    
    [self.navigationBar.navTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBar.defaultLeftButton.mas_right);
        make.right.equalTo(feedbackListButton.mas_left).offset(-kHalfMargin);
        make.height.mas_equalTo(self.navigationBar.navTitleLabel.w_textHeight);
        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
    }];
}

- (void)createSubviews {
    MJWeakSelf
    self.mainTableViewGroup.delegate = self;
    self.mainTableViewGroup.dataSource = self;
    self.mainTableViewGroup.backgroundColor = [UIColor hex_F8F8F8];

    [self.mainTableViewGroup registerClass:TL_FeedbackTextViewTableViewCell.class forCellReuseIdentifier:NSStringFromClass(TL_FeedbackTextViewTableViewCell.class)];
    [self.mainTableViewGroup registerClass:TL_FeedbackContactTableViewCell.class forCellReuseIdentifier:NSStringFromClass(TL_FeedbackContactTableViewCell.class)];
    [self.mainTableViewGroup registerClass:TL_FeedbackPhotoTableViewCell.class forCellReuseIdentifier:NSStringFromClass(TL_FeedbackPhotoTableViewCell.class)];

    [self.view addSubview:self.mainTableViewGroup];
    
    [self.mainTableViewGroup mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(PUB_NAVBAR_HEIGHT);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(SCREEN_HEIGHT - PUB_NAVBAR_HEIGHT);
    }];
    
    keyboardManager = [[TL_KeyboardManager alloc] initObserverWithAdaptiveMovementView:self.mainTableViewGroup];
    keyboardManager.keyboardHeightChanged = ^(CGFloat keyboardHeight, CGFloat shouldMoveDistance, CGRect shouldMoveFrame) {
        [weakSelf.mainTableViewGroup setWx_top:weakSelf.mainTableViewGroup.wx_top + shouldMoveDistance];
    };
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.questionArray.count + 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MJWeakSelf
    
    switch (indexPath.section) {

        case 0: {
            TL_FeedbackTextViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TL_FeedbackTextViewTableViewCell.className forIndexPath:indexPath];
            cell.textViewDidChange = ^(NSString * _Nonnull contentString) {
                weakSelf.contentString = contentString;
                
            };
            return cell;
        }
            break;
        case 1: {
            TL_FeedbackPhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TL_FeedbackPhotoTableViewCell.className forIndexPath:indexPath];
            cell.operationPhotosBlock = ^(NSMutableArray * _Nonnull photosSource) {
                weakSelf.dataSourceArray = photosSource;
            };
            return cell;
        }
            break;
        case 2: {
            TL_FeedbackContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TL_FeedbackContactTableViewCell.className forIndexPath:indexPath];
            cell.contactDidChange = ^(NSString * _Nonnull contactString) {
                weakSelf.contactString = contactString;
                
            };
            return cell;
        }
            break;
        
        default:
            break;
    }
    return [[UITableViewCell alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 300;
    }else if (indexPath.section==1) {
        return 180;
    }else if (indexPath.section==2) {
        return 68;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [TL_UIFactory view];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 3) {
        return PUB_TABBAR_OFFSET == 0 ? 10 : PUB_TABBAR_OFFSET;
    }
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PUB_TABBAR_OFFSET == 0 ? 10 : PUB_TABBAR_OFFSET)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}


- (void)giveUpSubmit {
    MJWeakSelf
    if (self.contentString.length > 0 || self.contactString.length > 0 || [TL_FeedbackPhotoManager sharedManager].isUploading || self.dataSourceArray.count > 0) {
        TL_AlertView *alert = [[TL_AlertView alloc] init];
        alert.alertViewDetailContent = WXLocalizedString(@"您有修改尚未提交，是否放弃修改？");
        alert.alertViewConfirmTitle = WXLocalizedString(@"确定");
        alert.alertViewCancelTitle = WXLocalizedString(@"取消");
        alert.confirmButtonClickBlock = ^{
            [weakSelf popViewController];
        };
        [alert showAlertView];
        return;
    }
    
    [self popViewController];
}

- (void)submitInfo {
    [TL_KeyboardManager hideKeyboard];
    
    if (self.contentString.length == 0 || self.contactString.length == 0 || ![self.contactString containsString:@"@"]) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:@"Please fill in all required information."];
        return;
    }
    
    if ([TL_FeedbackPhotoManager sharedManager].isUploading) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"图片正在上传中，请稍后")];
        return;
    }
    
    if (!TL_UserInfoManager.isLogin) {
        [TL_LoginViewController presentLoginView:nil];
        return;
    }
    
    NSMutableDictionary *t_dic = [NSMutableDictionary dictionary];
    [t_dic setObject:self.contentString forKey:@"content"];
    [t_dic setObject:self.contactString forKey:@"contactInfo"];
    if (self.dataSourceArray.count > 0) {
        NSMutableArray *imgs = [NSMutableArray arrayWithCapacity:3];
        for (TL_FeedbackPhotoModel *t_model in self.dataSourceArray) {
            [imgs addObject:t_model.img];
        }
        [t_dic setObject:[imgs componentsJoinedByString:@","] forKey:@"imageUrl"];
    }
    
    self.submitIsClick = YES;
    [self.mainTableViewGroup reloadData];
    
    MK_WEAK_SELF
    [APIManager sendPostRequest:[APIURLManager Feed_Back] parameters:t_dic model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        if (success) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:@"Submitted successfully!"];
            if (weakSelf.navigationController) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            }
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
        weakSelf.submitIsClick = NO;
        [weakSelf.mainTableViewGroup reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        weakSelf.submitIsClick = NO;
        [weakSelf.mainTableViewGroup reloadData];
    }];
    
}

- (void)netRequest {

}

- (void)dealloc {
    [keyboardManager stopKeyboardObserver];
}

@end
